package com.TripMate.system.service.impl;

import com.TripMate.system.AI.HttpSSE;
import com.TripMate.system.AI.MyWebSocket;
import com.TripMate.system.AI.Session;
import com.TripMate.system.common.ErrorCode;
import com.TripMate.system.exception.BusinessException;
import com.TripMate.system.mapper.AiHistoryMapper;
import com.TripMate.system.model.dto.chat.AiHistoryByMyQueryRequest;
import com.TripMate.system.model.dto.chat.AiHistoryQueryRequest;
import com.TripMate.system.model.dto.chat.ChatRequest;
import com.TripMate.system.model.entity.AiHistory;
import com.TripMate.system.model.vo.AiHistoryByMyVO;
import com.TripMate.system.model.vo.AiHistoryVO;
import com.TripMate.system.service.AiHistoryService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author dongmianyan
 * @description 针对表【ai_history(AI回答历史记录表)】的数据库操作Service实现
 * @createDate 2024-11-29 10:24:44
 */
@Service
public class AiHistoryServiceImpl extends ServiceImpl<AiHistoryMapper, AiHistory> implements AiHistoryService {
    private static final Logger logger = LoggerFactory.getLogger(AiHistoryService.class);

    private final MyWebSocket myWebSocket = new MyWebSocket();
    private final HttpSSE httpSSE = new HttpSSE();

    @Resource
    private AiHistoryMapper aiHistoryMapper;

    @Override
    public Flux<String> handleChat(ChatRequest chatRequest) {
        String sessionId = generateSessionId();
        String requestId = generateRequestId();

        // Log session and request IDs for debugging
        logger.info("Session ID: {}", sessionId);
        logger.info("Request ID: {}", requestId);

        return Flux.create(sink -> {
            try {
                if (chatRequest.isUseWebSocket()) {
                    // If using WebSocket, invoke the WebSocket method
                    String response = myWebSocket.webSocketInvoke(chatRequest.getContent(), sessionId, requestId);
                    sink.next(response);
                    sink.complete();
                } else {
                    // If using SSE, invoke the SSE method
                    CompletableFuture<String> future = httpSSE.sseInvoke(chatRequest.getContent(), sessionId, requestId);
                    future.thenAccept(sink::next).exceptionally(e -> {
                        sink.error(new RuntimeException("AI 服务错误: " + e.getMessage() + "请重新尝试", e));
                        return null;
                    });
                }
            } catch (Exception e) {
                sink.error(new RuntimeException("AI 服务错误: " + e.getMessage() + "请重新尝试", e));
            }
        });
    }

    @Override
    public String generateSessionId() {
        return Session.getSessionId();  // Generate unique session ID using utility
    }

    @Override
    public String generateRequestId() {
        return Session.getRequestId();  // Generate unique request ID using utility
    }

    /**
     * 查询全部的 AI 历史聊天记录。
     * @param pageParam
     * @param aidHistoryQueryRequest The query parameters for filtering and pagination.
     * @return
     */
    @Override
    public Page<AiHistoryVO> getQueryByAll(Page<AiHistoryVO> pageParam, AiHistoryQueryRequest aidHistoryQueryRequest) {
        // 自定义分页查询
        List<AiHistoryVO> aiHistoryVOS = aiHistoryMapper.getQueryByAll(pageParam, aidHistoryQueryRequest);
        if (aiHistoryVOS != null) {
            pageParam.setRecords(aiHistoryVOS);
            return pageParam;
        } else {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败");
        }
    }

    @Override
    public Page<AiHistoryVO> getQueryByMy(Page<AiHistoryVO> pageParam, AiHistoryByMyQueryRequest aidHistoryQueryRequest, Long userId) {
        if (aidHistoryQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        // 自定义分页查询
        List<AiHistoryVO> aiHistoryVOS = aiHistoryMapper.getQueryByMy(pageParam, aidHistoryQueryRequest, userId);
        if (aiHistoryVOS != null) {
            pageParam.setRecords(aiHistoryVOS);
            return pageParam;
        } else {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败");
        }
    }

}




